<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目详情 - xyUser System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link href="../styles/common.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Body styles are now in common.css */

        .project-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 0;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .project-image {
            max-width: 200px;
            max-height: 150px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            border: 3px solid rgba(255,255,255,0.2);
        }

        .container {
            background: white;
            border-radius: 15px 15px 0 0;
            box-shadow: 0 -5px 20px rgba(0,0,0,0.1);
            min-height: calc(100vh - 200px);
            margin-top: 0;
            padding-top: 30px;
        }

        .info-card {
            background: white;
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 25px;
            transition: all 0.3s ease;
            overflow: hidden;
        }

        .info-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.15);
        }

        .info-card h5 {
            color: #333;
            font-weight: 600;
            border-bottom: 2px solid #f8f9fa;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .qr-code {
            max-width: 200px;
            max-height: 200px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            border: 2px solid #e1e5e9;
        }

        .field-badge {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            padding: 8px 15px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .field-badge:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .stats-card {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(40, 167, 69, 0.3);
            transition: all 0.3s ease;
        }

        .stats-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(40, 167, 69, 0.4);
        }

        .back-btn {
            background: rgba(255,255,255,0.15);
            border: 2px solid rgba(255,255,255,0.3);
            color: white;
            border-radius: 25px;
            padding: 10px 20px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .back-btn:hover {
            background: rgba(255,255,255,0.25);
            border-color: rgba(255,255,255,0.5);
            color: white;
            transform: translateY(-2px);
        }

        .btn {
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-outline-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
        }

        .btn-outline-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(40, 167, 69, 0.3);
        }

        .btn-outline-info {
            background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%);
            color: white;
            border: none;
        }

        .btn-outline-info:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(23, 162, 184, 0.3);
        }

        .btn-outline-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
            border: none;
        }

        .btn-outline-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(255, 193, 7, 0.3);
        }

        .btn-outline-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            border: none;
        }

        .btn-outline-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(220, 53, 69, 0.3);
        }

        .btn-sm {
            padding: 6px 15px;
            font-size: 14px;
        }

        .table {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .table-light {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }

        .table-hover tbody tr:hover {
            background-color: rgba(102, 126, 234, 0.05);
        }

        .spinner-border {
            color: #667eea;
        }

        .text-primary {
            color: #667eea !important;
        }

        .text-success {
            color: #28a745 !important;
        }

        .text-info {
            color: #17a2b8 !important;
        }

        .text-warning {
            color: #ffc107 !important;
        }

        .text-danger {
            color: #dc3545 !important;
        }

        .text-secondary {
            color: #6c757d !important;
        }

        .badge {
            border-radius: 15px;
            padding: 0.5em 0.8em;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 0;
                border-radius: 0;
                padding: 15px;
            }
            
            .project-header {
                padding: 1.5rem 0;
            }
            
            .info-card {
                margin-bottom: 20px;
            }
            
            .stats-card {
                margin-top: 20px;
            }
        }

        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .info-card {
            animation: fadeInUp 0.6s ease-out;
        }

        .info-card:nth-child(2) {
            animation-delay: 0.1s;
        }

        .info-card:nth-child(3) {
            animation-delay: 0.2s;
        }

        .info-card:nth-child(4) {
            animation-delay: 0.3s;
        }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="bi bi-gear-fill me-2"></i>
                项目管理系统
            </a>
            <div class="navbar-nav ms-auto">
                <div class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                        <i class="bi bi-person-circle me-1"></i>
                        <span id="navbar-username">加载中...</span>
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="logout()">
                            <i class="bi bi-box-arrow-right me-2"></i>退出登录
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <!-- 项目头部 -->
    <div class="project-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <button class="btn back-btn mb-3" onclick="goBack()">
                        <i class="bi bi-arrow-left"></i> 返回项目管理
                    </button>
                    <div class="d-flex align-items-center">
                        <div id="projectImageContainer" class="me-4" style="display: none;">
                            <img id="projectImage" src="" alt="项目图片" class="project-image" loading="lazy">
                        </div>
                        <div>
                            <h1 id="projectName" class="mb-2">加载中...</h1>
                            <p id="projectDescription" class="mb-0 opacity-75">加载项目信息...</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 text-end">
                    <div class="stats-card p-3 rounded">
                        <h5 class="mb-1">总提交数</h5>
                        <h2 id="submissionCount" class="mb-0">-</h2>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <!-- 左侧：项目信息和表单配置 -->
            <div class="col-lg-8">
                <!-- 基本信息卡片 -->
                <div class="info-card p-4">
                    <h5 class="mb-3">
                        <i class="bi bi-info-circle text-primary"></i> 基本信息
                    </h5>
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>项目名称：</strong><span id="detailProjectName">-</span></p>
                            <p><strong>创建者：</strong><span id="projectOwner">-</span></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>创建时间：</strong><span id="projectCreatedAt">-</span></p>
                            <p><strong>项目ID：</strong><span id="projectId">-</span></p>
                        </div>
                    </div>
                    <div class="mt-3">
                        <strong>项目描述：</strong>
                        <p id="detailProjectDescription" class="text-muted mt-1">-</p>
                    </div>
                </div>

                <!-- 表单字段配置 -->
                <div class="info-card p-4">
                    <h5 class="mb-3">
                        <i class="bi bi-list-check text-success"></i> 表单字段配置
                    </h5>
                    <div id="fieldTypesContainer">
                        <div class="text-center text-muted">
                            <div class="spinner-border spinner-border-sm" role="status"></div>
                            <span class="ms-2">加载字段配置...</span>
                        </div>
                    </div>
                </div>

                <!-- 提交数据列表 -->
                <div class="info-card p-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="bi bi-table text-info"></i> 提交数据
                        </h5>
                        <button class="btn btn-outline-primary btn-sm" onclick="refreshSubmissions()">
                            <i class="bi bi-arrow-clockwise"></i> 刷新
                        </button>
                    </div>
                    <div id="submissionsContainer">
                        <div class="text-center text-muted">
                            <div class="spinner-border spinner-border-sm" role="status"></div>
                            <span class="ms-2">加载提交数据...</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：二维码和操作 -->
            <div class="col-lg-4">
                <!-- 二维码卡片 -->
                <div class="info-card p-4 text-center">
                    <h5 class="mb-3">
                        <i class="bi bi-qr-code text-warning"></i> 项目二维码
                    </h5>
                    <div id="qrCodeContainer">
                        <div class="text-muted">
                            <div class="spinner-border spinner-border-sm" role="status"></div>
                            <p class="mt-2">生成二维码中...</p>
                        </div>
                    </div>
                    <button class="btn btn-primary mt-3" onclick="generateNewQRCode()">
                        <i class="bi bi-arrow-clockwise"></i> 重新生成二维码
                    </button>
                </div>

                <!-- 操作按钮 -->
                <div class="info-card p-4">
                    <h5 class="mb-3">
                        <i class="bi bi-gear text-secondary"></i> 操作
                    </h5>
                    <div class="d-grid gap-2">
                        <button class="btn btn-outline-success" onclick="exportSubmissions()">
                            <i class="bi bi-download"></i> 导出数据
                        </button>
                        <button class="btn btn-outline-info" onclick="viewSubmissionStats()">
                            <i class="bi bi-bar-chart"></i> 数据统计
                        </button>
                        <button class="btn btn-outline-warning" onclick="editProject()">
                            <i class="bi bi-pencil"></i> 编辑项目
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentProject = null;
        let projectSubmissions = [];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadProjectDetail();
        });

        // 检查认证状态
        async function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
                return;
            }
        }

        // 获取URL中的项目ID
        function getProjectIdFromUrl() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('id');
        }

        // 加载项目详情
        async function loadProjectDetail() {
            const projectId = getProjectIdFromUrl();
            if (!projectId) {
                alert('无效的项目ID');
                goBack();
                return;
            }

            const token = localStorage.getItem('token');
            try {
                // 加载项目基本信息
                const response = await fetch(`/projects/${projectId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('获取项目信息失败');
                }

                currentProject = await response.json();
                displayProjectInfo(currentProject);
                
                // 加载提交数据
                await loadSubmissions(projectId);
                
                // 生成二维码
                await generateQRCode(projectId);
                
            } catch (error) {
                console.error('加载项目详情失败:', error);
                alert('加载项目详情失败: ' + error.message);
            }
        }

        // 显示项目信息
        function displayProjectInfo(project) {
            document.getElementById('projectName').textContent = project.name || '未命名项目';
            document.getElementById('projectDescription').innerHTML = project.description || '暂无描述';
            document.getElementById('detailProjectName').textContent = project.name || '未命名项目';
            document.getElementById('detailProjectDescription').innerHTML = project.description || '暂无描述';
            document.getElementById('projectOwner').textContent = project.owner?.username || '未知';
            document.getElementById('projectId').textContent = project.id;
            
            if (project.createdAt) {
                document.getElementById('projectCreatedAt').textContent = new Date(project.createdAt).toLocaleString();
            }

            // 显示项目图片
            if (project.mainImage) {
                document.getElementById('projectImage').src = project.mainImage;
                document.getElementById('projectImageContainer').style.display = 'block';
            }

            // 显示表单字段配置
            displayFieldTypes(project.fieldTypes || []);
        }

        // 显示表单字段类型
        function displayFieldTypes(fieldTypes) {
            const container = document.getElementById('fieldTypesContainer');
            
            if (fieldTypes.length === 0) {
                container.innerHTML = '<p class="text-muted">未配置表单字段</p>';
                return;
            }

            const fieldsHtml = fieldTypes.map(field => `
                <span class="badge field-badge me-2 mb-2 p-2">
                    <i class="bi bi-${getFieldIcon(field.type)}"></i>
                    ${field.name}
                    ${field.required ? '<i class="bi bi-asterisk text-danger ms-1" title="必填"></i>' : ''}
                </span>
            `).join('');

            container.innerHTML = fieldsHtml;
        }

        // 获取字段类型对应的图标
        function getFieldIcon(type) {
            const iconMap = {
                'text': 'type',
                'email': 'envelope',
                'phone': 'telephone',
                'number': 'hash',
                'textarea': 'text-paragraph',
                'select': 'list',
                'radio': 'record-circle',
                'checkbox': 'check-square',
                'file': 'file-earmark',
                'date': 'calendar',
                'time': 'clock'
            };
            return iconMap[type] || 'question-circle';
        }

        // 加载提交数据
        async function loadSubmissions(projectId) {
            const token = localStorage.getItem('token');
            try {
                const response = await fetch(`/submissions/project/${projectId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    projectSubmissions = await response.json();
                    displaySubmissions(projectSubmissions);
                    document.getElementById('submissionCount').textContent = projectSubmissions.length;
                } else {
                    throw new Error('获取提交数据失败');
                }
            } catch (error) {
                console.error('加载提交数据失败:', error);
                document.getElementById('submissionsContainer').innerHTML = 
                    '<p class="text-danger">加载提交数据失败</p>';
                document.getElementById('submissionCount').textContent = '0';
            }
        }

        // 显示提交数据
        function displaySubmissions(submissions) {
            const container = document.getElementById('submissionsContainer');
            
            if (submissions.length === 0) {
                container.innerHTML = '<p class="text-muted text-center py-4">暂无提交数据</p>';
                return;
            }

            const tableHtml = `
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>提交时间</th>
                                <th>提交数据</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${submissions.map(submission => `
                                <tr>
                                    <td>${new Date(submission.createdAt).toLocaleString()}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-info" onclick="viewSubmissionDetail(${submission.id})">
                                            <i class="bi bi-eye"></i> 查看详情
                                        </button>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-danger" onclick="deleteSubmission(${submission.id})">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;

            container.innerHTML = tableHtml;
        }

        // 生成二维码
        async function generateQRCode(projectId) {
            const token = localStorage.getItem('token');
            try {
                const response = await fetch(`/project-shares/project/${projectId}`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const projectShare = await response.json();
                    displayQRCode(projectShare.qrCodeData, projectShare.shareToken);
                } else {
                    throw new Error('生成二维码失败');
                }
            } catch (error) {
                console.error('生成二维码失败:', error);
                document.getElementById('qrCodeContainer').innerHTML = 
                    '<p class="text-danger">生成二维码失败</p>';
            }
        }

        // 显示二维码
        function displayQRCode(qrCodeData, shareToken) {
            const container = document.getElementById('qrCodeContainer');
            container.innerHTML = `
                <img src="${qrCodeData}" class="img-fluid qr-code" alt="项目二维码" id="detailQrCodeImage">
                <p class="text-muted small mt-2">分享标识: ${shareToken}</p>
                <p class="text-info small">扫描二维码访问项目提交页面</p>
                <div class="mt-3">
                    <button class="btn btn-outline-primary btn-sm" onclick="downloadQRCodeImage('${qrCodeData}', '${currentProject.name}')">
                        <i class="bi bi-download"></i> 下载二维码
                    </button>
                </div>
            `;
        }

        // 返回项目管理页面
        function goBack() {
            window.location.href = 'project-management.html';
        }

        // 刷新提交数据
        async function refreshSubmissions() {
            const projectId = getProjectIdFromUrl();
            if (projectId) {
                await loadSubmissions(projectId);
            }
        }

        // 重新生成二维码
        async function generateNewQRCode() {
            const projectId = getProjectIdFromUrl();
            if (projectId) {
                document.getElementById('qrCodeContainer').innerHTML = `
                    <div class="text-muted">
                        <div class="spinner-border spinner-border-sm" role="status"></div>
                        <p class="mt-2">重新生成中...</p>
                    </div>
                `;
                await generateQRCode(projectId);
            }
        }

        // 查看提交详情
        function viewSubmissionDetail(submissionId) {
            const submission = projectSubmissions.find(s => s.id === submissionId);
            if (submission) {
                alert('提交详情:\n' + JSON.stringify(submission.data, null, 2));
            }
        }

        // 删除提交
        async function deleteSubmission(submissionId) {
            if (!confirm('确定要删除这条提交数据吗？')) {
                return;
            }

            const token = localStorage.getItem('token');
            try {
                const response = await fetch(`/submissions/${submissionId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    alert('删除成功');
                    await refreshSubmissions();
                } else {
                    throw new Error('删除失败');
                }
            } catch (error) {
                console.error('删除提交失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 导出数据
        function exportSubmissions() {
            if (projectSubmissions.length === 0) {
                alert('暂无数据可导出');
                return;
            }

            const csvContent = generateCSV(projectSubmissions);
            downloadCSV(csvContent, `${currentProject.name}_submissions.csv`);
        }

        // 生成CSV内容
        function generateCSV(submissions) {
            if (submissions.length === 0) return '';

            const headers = ['提交时间', '提交数据'];
            const rows = submissions.map(submission => [
                new Date(submission.createdAt).toLocaleString(),
                JSON.stringify(submission.data)
            ]);

            return [headers, ...rows].map(row => 
                row.map(field => `"${field}"`).join(',')
            ).join('\n');
        }

        // 下载CSV文件
        function downloadCSV(content, filename) {
            const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 查看数据统计
        function viewSubmissionStats() {
            alert('数据统计功能开发中...');
        }

        // 编辑项目
        function editProject() {
            alert('编辑项目功能开发中...');
        }

        // 下载二维码图片 - 兼容手机端
        function downloadQRCodeImage(qrCodeData, projectName) {
            try {
                // 检测是否为移动设备
                const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
                const isWeChat = /MicroMessenger/i.test(navigator.userAgent);
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = qrCodeData;
                link.download = `${projectName}_二维码.png`;
                
                if (isMobile) {
                    if (isWeChat) {
                        // 微信浏览器中，显示提示信息
                        alert('请长按二维码图片，选择"保存图片"来下载');
                        return;
                    } else {
                        // 移动端浏览器，尝试直接下载
                        link.target = '_blank';
                    }
                }
                
                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                // 如果是移动端但不是微信，显示备用提示
                if (isMobile && !isWeChat) {
                    setTimeout(() => {
                        alert('如果下载未开始，请长按二维码图片选择"保存图片"');
                    }, 1000);
                }
                
            } catch (error) {
                console.error('下载失败:', error);
                alert('下载失败，请长按二维码图片选择"保存图片"');
            }
        }
    </script>
</body>
</html>